package com.test.thread;

/**
 * Created by jl on 2018/3/1.
 * thread local与普通变量方式比较：thread local无并发问题而普通变量有并发问题
 * 但thread local中真正存储这些键值对的Entry的key却是WeakReference的，在系统gc时会被回收，导致value永远没法被访问，
 * 如果不再访问该localmap（访问时会清掉那些key为null的value），容易内存泄漏
 */
public class ThreadLocalDemo {
    private static final ThreadLocal<Integer> THREAD_LOCAL = new ThreadLocal<Integer>();
    private static int value;

    public static void main(String[] args) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                int i = (int) (Math.random() * 100);
                //thread local方式
                THREAD_LOCAL.set(i);
                //普通变量方式
                value = i;
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "; threadLocal->" + THREAD_LOCAL.get() + "; value->" + value);
            }
        };
        Thread thread1 = new Thread(runnable);
        Thread thread2 = new Thread(runnable);
        thread1.start();
        thread2.start();
    }
}
